package site.zhouinfo.tree.trie;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author zhou
 * @create 2017-08-02 13:05
 * @email zhouinfo@qq.com
 * @blog blog.zhouinfo.site
 */
public class Trie {

    private TrieNode root;

    public Trie() {
        root = new TrieNode();
        root.wordEnd = false;
    }

    public void insert(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            Character c = word.charAt(i);
            if (!node.childNode.containsKey(c)) {
                node.childNode.put(c, new TrieNode());
            }
            node = node.childNode.get(c);
        }
        node.wordEnd = true;
    }

    public boolean search(String word) {
        TrieNode node = root;
        boolean found = true;
        for (int i = 0; i < word.length(); i++) {
            Character c = word.charAt(i);
            if (!node.childNode.containsKey(c)) {
                return false;
            }
            node = node.childNode.get(c);
        }
        return found && node.wordEnd;
    }

    public boolean startsWith(String prefix) {
        TrieNode node = root;
        boolean found = true;
        for (int i = 0; i < prefix.length(); i++) {
            Character c = prefix.charAt(i);
            if (!node.childNode.containsKey(c)) {
                return false;
            }
            node = node.childNode.get(c);
        }
        return found;
    }

    /**
     * 以行为单位读取文件内容，一次读一整行：
     *
     * @param filePath
     */
    public void insertByFile(String filePath) {
        File file = new File(filePath);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                insert(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }
}

